//
//  BK_my_EvaluationOfDryingCell3.m
//  bestkeep
//
//  Created by 李明 on 2016/11/30.
//  Copyright © 2016年 utouu. All rights reserved.
//

#import "BK_my_EvaluationOfDryingCell3.h"
#import "Masonry.h"
#import "BKMyCommon.h"
#import "BK_my_EvaluationPhotoVC.h"

#define IOS8 ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0 ? YES : NO)

@implementation BK_my_EvaluationOfDryingCell3

- (void)awakeFromNib {
    [super awakeFromNib];
}

- (void)initializeCell:(CellModel *)cellModel {
    self.vc = cellModel.delegate;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        _photos = [NSMutableArray array];
        _maxPictureCount = 8;
        [self creatUI];
        self.backgroundColor = [UIColor clearColor];
    }
    return self;
}

- (void)creatUI {
    
    //背景颜色
    UIView *backView = [[UIView alloc] init];
    backView.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:backView];
    [backView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView.mas_top).offset(2);
        make.left.mas_equalTo(self.contentView.mas_left);
        make.right.mas_equalTo(self.contentView.mas_right);
        make.height.mas_equalTo(36);
    }];
    _addDryingPictureLabel = [[UILabel alloc] init];
    _addDryingPictureLabel.text = @"添加晒单图片";
    _addDryingPictureLabel.font = [UIFont systemFontOfSize:15.0];
    _addDryingPictureLabel.textColor = HexColor(0x404040);
    _addDryingPictureLabel.backgroundColor = [UIColor whiteColor];
    [self.contentView addSubview:_addDryingPictureLabel];
    [_addDryingPictureLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView.mas_top).offset(2);
        make.left.mas_equalTo(self.contentView.mas_left).offset(ApplicationBackGauge);
        make.width.mas_equalTo(ScreenWidth-ApplicationBackGauge*2);
        make.height.mas_equalTo(36);
    }];

    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((ScreenWidth - 30 - 50 - ApplicationBackGauge) / 4, (ScreenWidth - 30 - 50 - ApplicationBackGauge) / 4);
    layout.sectionInset = UIEdgeInsetsMake(0, ApplicationBackGauge, 0, 50);
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    layout.footerReferenceSize = CGSizeMake(ScreenWidth, 35);
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    _collectionView.backgroundColor = [UIColor whiteColor];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collectionViewCell"];
    
    [_collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer"];
    [self.contentView addSubview:_collectionView];
    [self collectionViewConstraints];
}

- (void)updateCollectionViewConstraints {
    [_collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView.mas_top).offset(38);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset(3);
        make.left.mas_equalTo(self.contentView.mas_left).offset(0);
        make.right.mas_equalTo(self.contentView.mas_right).offset(0);
    }];
}

- (void)collectionViewConstraints {
    [self.collectionView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView.mas_top).offset(38);
        make.bottom.mas_equalTo(self.contentView.mas_bottom).offset( -ScreenWidth / 4 + 15);
        make.left.mas_equalTo(self.contentView.mas_left).offset(0);
        make.right.mas_equalTo(self.contentView.mas_right).offset(0);
    }];
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionFooter) {
        UICollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"footer" forIndexPath:indexPath];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(ApplicationBackGauge, 0, footer.bounds.size.width-ApplicationBackGauge*2, footer.bounds.size.height)];
        label.text = @"最多上传8张,每张不超过5M,支持PNG、JPG";
        label.textColor = HexColor(0xB2B2B2);
        label.font = [UIFont systemFontOfSize:12.0];
        [footer addSubview:label];
        label.backgroundColor = [UIColor whiteColor];
        footer.backgroundColor = [UIColor whiteColor];
        return footer;
    }
    return nil;
}
//
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.photos.count >= _maxPictureCount) {
        return _maxPictureCount;
    }
    return self.photos.count + 1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collectionViewCell" forIndexPath:indexPath];
    cell.layer.cornerRadius = 3;
    cell.layer.borderColor = RGBCOLOR(221, 221, 221, 1).CGColor;
    cell.layer.borderWidth = .5;
    cell.clipsToBounds = YES;
    for (UIView *view in cell.subviews) {
        if (view) {
            [view removeFromSuperview];
        }
    }
    if (indexPath.row == self.photos.count) {
        CGFloat w = cell.bounds.size.width / 2;
        UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(w / 2, w - 1, w, 1)];
        line1.backgroundColor = RGBCOLOR(221, 221, 221, 1);
        UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake(w - 1, w / 2, 1, w)];
        line2.backgroundColor = RGBCOLOR(221, 221, 221, 1);
        [cell addSubview:line2];
        [cell addSubview:line1];
        if (self.photos.count > 0) {
        }
    } else {
        UIImageView *photo = [[UIImageView alloc] initWithFrame:cell.bounds];
        photo.image = self.photos[indexPath.row];
        [cell addSubview:photo];
    }
    return cell;
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto {
    [self.photos addObjectsFromArray:photos];
    if (self.photos.count > 3) {
        [self updateCollectionViewConstraints];
    }
    [self.collectionView reloadData];
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == self.photos.count) {
        if (IOS8) {
            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
            
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    [self pushPickerViewController:UIImagePickerControllerSourceTypeCamera];

                }];
                [alertController addAction:action1];
            }
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"从相册中选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                [self addPhotoAlbum];
            }];
            UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            [alertController addAction:cancelAction];
            [alertController addAction:action2];
            [self.vc presentViewController:alertController animated:YES completion:nil];
        } else {
            UIActionSheet *sheet;
            if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
                sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"" otherButtonTitles:@"从相册选择",@"拍照", nil];
            } else {
            
                sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"从相册选择", nil];
            }
            [sheet showInView:self];
        }
    } else {
        BK_my_EvaluationPhotoVC *photoVC = [[BK_my_EvaluationPhotoVC alloc] init];
        photoVC.photos = self.photos;
        photoVC.currentIndex = indexPath.row;
        photoVC.deletePhotoBlock = ^(NSInteger index) {
            [self.photos removeObjectAtIndex:index];
            if (self.photos.count < 4) {
                [self collectionViewConstraints];
            }
            [self.collectionView reloadData];
        };
        [self.vc presentViewController:photoVC animated:YES completion:nil];
    }
}

- (void)addPhotoAlbum {
    TZImagePickerController *tzImage = [[TZImagePickerController alloc] initWithMaxImagesCount:_maxPictureCount delegate:self];
    tzImage.maxImagesCount = _maxPictureCount - self.photos.count;
    [self.vc presentViewController:tzImage animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    NSString *mediaType = info[UIImagePickerControllerMediaType];
    NSData *imageData = nil;
    if ([mediaType isEqualToString:@"public.image"]) {
        UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
        UIImage *img = [self cutImage:picker.view];
        CGRect rect = CGRectMake(picker.view.frame.size.width / 2 - 100, picker.view.frame.size.height / 2 - 100, 200, 200);
        CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], rect);
        CGImageRelease(imageRef);
        imageData = UIImagePNGRepresentation(image);
        [self.photos addObject:image];
        if (self.photos.count > 3) {
            [self updateCollectionViewConstraints];
        }
        [self.collectionView reloadData];
        UIImageWriteToSavedPhotosAlbum(image, self, nil, nil);
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (UIImage *)cutImage:(UIView *)view {
    CGSize size = CGSizeMake(view.frame.size.height, view.frame.size.height);
    UIGraphicsBeginImageContext(size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    [view.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSUInteger sourceType = 0;
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        switch ((NSInteger)buttonIndex) {
            case 0:
                sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                [self addPhotoAlbum];
                break;
            case 1:
                sourceType = UIImagePickerControllerSourceTypeCamera;
                break;
            default:
                break;
        }
    } else {
        if (buttonIndex == 0) {
            sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            [self addPhotoAlbum];
        } else {
            return;
        }
    }
    [self pushPickerViewController:sourceType];
}

- (void)pushPickerViewController:(UIImagePickerControllerSourceType)type {
    UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
    imagePickerController.delegate = self;
    imagePickerController.allowsEditing = YES;
    imagePickerController.sourceType = type;
    imagePickerController.navigationBar.barTintColor = [UIColor whiteColor];
    [self.vc presentViewController:imagePickerController animated:YES completion:nil];
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}

@end
